package com.jonsnowsword.wifiassistant;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.jonsnowsword.wifiassistant.GoogleAnalyticsApplication.TrackerName;

public class WifiConnectActivity extends Activity {

	
	private WifiManager wifiManager;  
	List<ScanResult> list;  
	private TextView connectedWifiName;
	private TextView connectedWifiIp;
	private MyHandler myHandler;
	private OnItemClickListenerImpl  onItemClickListener;
	private List<Wifi> wifiInfos;
	private String password;
	private InterstitialAd interstitialAd;
	private static boolean isExit;
	private static boolean isLoad;
	private static boolean isFirst=true;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wifi_connect);
		connectedWifiName=(TextView)findViewById(R.id.connectedWifiName);
		connectedWifiIp=(TextView)findViewById(R.id.connectedWifiIp);
		myHandler = new MyHandler(WifiConnectActivity.this);
		onItemClickListener = new OnItemClickListenerImpl(WifiConnectActivity.this);

		if(isFirst==true)
		{
			FileUtil.checkFile(isFirst);
			isFirst=false;
		}
		adinit();
		init();
		
	}


	
	@Override
	protected void onResume() {
		// TODO 自动生成的方法存根
		sendGoogleAnalyticsView();
		super.onResume();
	}



	Tracker mTracker;

	public void sendGoogleAnalyticsView()
	{
		// Get tracker.
		mTracker = ((GoogleAnalyticsApplication) getApplication()).getTracker(TrackerName.GLOBAL_TRACKER);

		// Set screen name.
		// Where path is a String representing the screen name.
		mTracker.setScreenName("WifiConnectActivity");

		// Send a screen view.
		mTracker.send(new HitBuilders.AppViewBuilder().build());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	private void init() {  
		isExit = false;
		wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);   
		new Thread(new Runnable() 
			{
				@Override
				public void run() 
				{
					int tmp=10;
					while(tmp>0)
					{
		        		WifiInfo wifiInfo1=wifiManager.getConnectionInfo();
						String ssid1 = FileUtil.check(wifiInfo1.getSSID());
						int ipAddress1 = wifiInfo1.getIpAddress();  
						if(ssid1!=null&&ipAddress1!=0)
						{ 	
             			    String ipString1 = "";
             			    if (ipAddress1 != 0) 
             			    	ipString1 = ((ipAddress1 & 0xff) + "." + (ipAddress1 >> 8 & 0xff) + "." + (ipAddress1 >> 16 & 0xff) + "." + (ipAddress1 >> 24 & 0xff));  
             			    Message mes=myHandler.obtainMessage();
		                	mes.what=0x114;
             			    Bundle bu=new Bundle();
		                	bu.putString("ssid", ssid1);
		                	bu.putString("ipString", ipString1);
		                	mes.setData(bu);  
		                	myHandler.sendMessage(mes);
		                	break;
						}
						if(ssid1!=null)
						{
             			    Message mes=myHandler.obtainMessage();
		                	mes.what=0x114;
             			    Bundle bu=new Bundle();
		                	bu.putString("ssid", ssid1);
		                	bu.putString("ipString", null);
		                	mes.setData(bu);  
		                	myHandler.sendMessage(mes);
						}
						if(ssid1==null)
						{
             			    Message mes=myHandler.obtainMessage();
		                	mes.what=0x114;
             			    Bundle bu=new Bundle();
		                	bu.putString("ssid", "No wifi connected");
		                	bu.putString("ipString", null);
		                	mes.setData(bu);  
		                	myHandler.sendMessage(mes);
						}
						try {
								Thread.sleep(1000);
						} 
						catch (InterruptedException e) {
								e.printStackTrace();
						}
						tmp--;
					}
				}


			}).start();
 
       
        Button wifiChangeView=(Button)findViewById(R.id.wifiChangeButton);
        if (!wifiManager.isWifiEnabled())
        {
        	wifiChangeView.setText("Open Wifi");
        }
        else
        {
        	wifiChangeView.setText("Turn off Wifi");
        }
        
        

        WifiPassword wifiPassword = new WifiPassword();
		try {
			wifiInfos = wifiPassword.Read();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

        
        list = wifiManager.getScanResults();  
        ListView listView = (ListView) findViewById(R.id.listView1);  
        if (list == null) {   
        }else {  
        	
        	list=arrange(list);
        	if(list!=null)
        		
        	{
                listView.setAdapter(new MyAdapter(this,list));
                
                listView.setOnItemClickListener(onItemClickListener);
                onItemClickListener.setMyHandler(myHandler);
        	}

        }  
          
    }  
	
	 private List<ScanResult> arrange(List<ScanResult> list2) {
		// TODO Auto-generated method stub

		 List<ScanResult> list3=new ArrayList<ScanResult>();
		 List<ScanResult> list=new ArrayList<ScanResult>();
		 if(list2.size()==0)
		 {
			 return list;
		 }
		 for(int i=list2.size()-1;i>=0;i--)
		 {
			 if(String.valueOf(list2.get(i).capabilities).equals("[ESS]"))
			 {
				 list3.add(list2.get(i));
				 list2.remove(i);
			 }
		 }
		 
		 
		 for(int i=0;i<list3.size();i++)
		 {
			 list.add(list3.get(i));
		}
		 for(int i=0;i<list2.size();i++)
		 {
			 list.add(list2.get(i));
		 }
		 return list;
		 
		
	}

	public class MyAdapter extends BaseAdapter {  
   	  
	        LayoutInflater inflater;  
	        List<ScanResult> list;  
	        public MyAdapter(Context context, List<ScanResult> list) {  
	            // TODO Auto-generated constructor stub  
	            this.inflater = LayoutInflater.from(context);  
	            this.list = list;  
	        }  
	  
	        @Override  
	        public int getCount() {  
	            // TODO Auto-generated method stub  
	            return list.size();  
	        }  
	  
	        @Override  
	        public Object getItem(int position) {  
	            // TODO Auto-generated method stub  
	            return list.get(position);  
	        }  
	  
	        @Override  
	        public long getItemId(int position) {  
	            // TODO Auto-generated method stub  
	            return position;  
	        }  
	  
	        @Override  
	        public View getView(int position, View convertView, ViewGroup parent) {  
	            // TODO Auto-generated method stub  
	            View view = null;  
	            view = inflater.inflate(R.layout.item_wifi_list, null);  
	            ScanResult scanResult = list.get(position);  
	            TextView textView1 = (TextView) view.findViewById(R.id.wifiNameView1);  
	            textView1.setText(scanResult.SSID+" ( "+scanResult.BSSID+" ) ");  
 
	            TextView textView2 = (TextView) view.findViewById(R.id.wifiLevelView);  
	            textView2.setText(String.valueOf(scanResult.level)+" dBM");  
	            ImageView strengthView = (ImageView) view.findViewById(R.id.strength);
	            setStrength(Math.abs(scanResult.level),strengthView);

	            
	            TextView textView3 = (TextView) view.findViewById(R.id.wifiCapabilitiesView1);  
	            textView3.setText(getCapabilities(String.valueOf(scanResult.capabilities))); 
	            
	            ImageView imageView = (ImageView) view.findViewById(R.id.freeWifiView1); 
	            ImageView imageView2 = (ImageView) view.findViewById(R.id.WifiView1);  
	            if(!String.valueOf(scanResult.capabilities).equals("[ESS]"))
	            {
	            	imageView.setVisibility(View.GONE);
	            	imageView2.setImageResource(R.drawable.wifi_lock);
	            }
	            return view;  
	        }

			private void setStrength(int y, ImageView strengthView) {
				// TODO Auto-generated method stub
				switch(y)
				{
					case 100:
						strengthView.setImageResource(R.drawable.strength100);
						break;
					case 99:
					case 98:
					case 97:
						strengthView.setImageResource(R.drawable.strength97);
						break;
					case 96:
					case 95:
					case 94:
						strengthView.setImageResource(R.drawable.strength94);
						break;
					case 93:
					case 92:
					case 91:
						strengthView.setImageResource(R.drawable.strength91);
						break;
					case 90:
					case 89:
					case 88:
						strengthView.setImageResource(R.drawable.strength88);
						break;
					case 87:
					case 86:
					case 85:
						strengthView.setImageResource(R.drawable.strength85);
						break;
					case 84:
					case 83:
					case 82:
						strengthView.setImageResource(R.drawable.strength82);
						break;
					case 81:
					case 80:
					case 79:
						strengthView.setImageResource(R.drawable.strength79);
						break;
					case 78:
					case 77:
					case 76:
						strengthView.setImageResource(R.drawable.strength76);
						break;
					case 75:
					case 74:
					case 73:
						strengthView.setImageResource(R.drawable.strength73);
						break;
					case 72:
					case 71:
					case 70:
						strengthView.setImageResource(R.drawable.strength70);
						break;
					case 69:
					case 68:
					case 67:
						strengthView.setImageResource(R.drawable.strength67);
						break;
					case 66:
					case 65:
					case 64:
						strengthView.setImageResource(R.drawable.strength64);
						break;
					case 63:
					case 62:
					case 61:
						strengthView.setImageResource(R.drawable.strength61);
						break;
					case 60:
					case 59:
					case 58:
						strengthView.setImageResource(R.drawable.strength58);
						break;
					case 57:
					case 56:
					case 55:
						strengthView.setImageResource(R.drawable.strength55);
						break;
					case 54:
					case 53:
					case 52:
						strengthView.setImageResource(R.drawable.strength52);
						break;
					case 51:
					case 50:
					case 49:
						strengthView.setImageResource(R.drawable.strength49);
						break;
					case 48:
					case 47:
					case 46:
						strengthView.setImageResource(R.drawable.strength46);
						break;
					case 45:
					case 44:
					case 43:
						strengthView.setImageResource(R.drawable.strength43);
						break;
					default:
				
				}
	            
			}  
	

	 }

	private class OnItemClickListenerImpl implements OnItemClickListener {

		private Context context;
		private MyHandler myHandler;
				
		public void setMyHandler(MyHandler myHandler) {
			this.myHandler = myHandler;
		}
		public OnItemClickListenerImpl(Context context)
		{
			this.context=context;
		}
			
			
			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position,  long id) 
			{
				final ScanResult scanResult=(ScanResult) arg0.getItemAtPosition(position);
				switch(Integer.parseInt(WifiConnect.pdjm(scanResult.capabilities)))
				{
					case 1:
	   				 	new AlertDialog.Builder(WifiConnectActivity.this)
		    	          .setTitle(scanResult.SSID)
		    	          .setItems(new String[] { "Capabilities"+":"+getCapabilities(String.valueOf(scanResult.capabilities)), "Signal Strength"+":"+Math.abs(scanResult.level) }, null)
		    	          .setNegativeButton("Cancel", null) 
		    	          .setPositiveButton("Connect", new OnClickListener() 
		    	          {
								@Override
								public void onClick(DialogInterface dialog, int which) 
								{									
						        	connectedWifiName.setText("Connecting...");
						            connectedWifiIp.setText(null);
									WifiConfiguration wifiConfig=WifiConnect.CreateWifiInfo(scanResult.SSID, "", WifiConnect.pdjm(scanResult.capabilities),wifiManager);
					     			int wcgID = wifiManager.addNetwork(wifiConfig);
					     			
					     			if(wifiManager.enableNetwork(wcgID, true))
					     			{
					     				new Thread(new Runnable() 
					     				{
		 									@Override
		 									public void run() 
		 									{
		 										int tmp = 11;
		 										while(tmp>0)
		 										{
		 											WifiInfo wifiInfo1=wifiManager.getConnectionInfo();
		 											String ssid1 = FileUtil.check(wifiInfo1.getSSID());
		 											int ipAddress1 = wifiInfo1.getIpAddress();  
		 											if(ssid1!=null&&ipAddress1!=0)
		 											{ 		
		 												final String password=FileUtil.read(scanResult.SSID);
		 												if(password==null)
		 													FileUtil.write(scanResult.SSID,"empty","");
		 							     				String ipString1 = "";
		 				             			        if (ipAddress1 != 0) 
		 				             			        	ipString1 = ((ipAddress1 & 0xff) + "." + (ipAddress1 >> 8 & 0xff) + "." + (ipAddress1 >> 16 & 0xff) + "." + (ipAddress1 >> 24 & 0xff));  
		 				             			        Message mes=myHandler.obtainMessage();
									                	mes.what=0x114;
		 				             			        Bundle bu=new Bundle();
									                	bu.putString("ssid", ssid1);
									                	bu.putString("ipString", ipString1);
									                	mes.setData(bu);  
									                	myHandler.sendMessage(mes);
														break;
														
													}
		 											try {
		 												Thread.sleep(1000);
		 											} 
		 											catch (InterruptedException e) {
		 												e.printStackTrace();
		 											}
		 											tmp--;		 											
		 										}
		 										if(tmp==0)
		 										{
		 											Message mes=myHandler.obtainMessage();
								                	mes.what=0x110;
	 				             			        Bundle bu=new Bundle();
								                	bu.putString("ssid", scanResult.SSID);
								                	mes.setData(bu);  
								                	myHandler.sendMessage(mes);
		 										}
		 										
		 									}
		 								}).start(); 
					     			}		
					     			else
					     			{
					     				Message mes=myHandler.obtainMessage();
					                	mes.what=0x110;
			             			        Bundle bu=new Bundle();
					                	bu.putString("ssid", scanResult.SSID);
					                	mes.setData(bu);  
					                	myHandler.sendMessage(mes);
					     			}
								}
							}).show();   
	   				 	break;
					default:
						password=FileUtil.read(scanResult.SSID);
						if(password==null)
						{
							if(wifiInfos.size()!=0)
							{
								for(int i=0;i<wifiInfos.size();i++)
								{
									if(wifiInfos.get(i).getSsid().equals(scanResult.SSID))
									{
										password=wifiInfos.get(i).getPassword();
									}
								}
							}
						}
						if(password==null||password.equals(""))
						{
							final EditText  editText=new EditText(context);
							editText.setInputType(0x81);
			            	new AlertDialog.Builder(WifiConnectActivity.this)
			    	          .setTitle(scanResult.SSID)
			    	          .setItems(new String[] { "Capabilities"+":"+getCapabilities(String.valueOf(scanResult.capabilities)), "Signal Strength"+":"+Math.abs(scanResult.level) }, null)
			    	          .setView(editText)
			    	          .setNegativeButton("Cancel", null) 
			    	          .setPositiveButton("Connect", new OnClickListener() 
			    	          {
			    	        	  	@Override
									public void onClick(DialogInterface dialog, int which) 
									{						        	
										
					                	WifiConfiguration wifiConfig=WifiConnect.CreateWifiInfo(scanResult.SSID, editText.getText().toString(), WifiConnect.pdjm(scanResult.capabilities),wifiManager);
			             			    int wcgID = wifiManager.addNetwork(wifiConfig);
			             				if(wifiManager.enableNetwork(wcgID, true))
			             				{
			             					connectedWifiName.setText("Connecting...");
								            connectedWifiIp.setText(null);
			             					new Thread(new Runnable() 
			             					{
			 									@Override
			 									public void run() 
			 									{

			 										int tmp = 11;
			 										while(tmp>0)
			 										{
			 											WifiInfo wifiInfo1=wifiManager.getConnectionInfo();
			 											String ssid1 = FileUtil.check(wifiInfo1.getSSID());
			 											int ipAddress1 = wifiInfo1.getIpAddress();  
			 											if(ssid1!=null&&ipAddress1!=0)
			 											{ 	
			 												String ipString1 = "";
			 				             			        if (ipAddress1 != 0) 
			 				             			        	ipString1 = ((ipAddress1 & 0xff) + "." + (ipAddress1 >> 8 & 0xff) + "." + (ipAddress1 >> 16 & 0xff) + "." + (ipAddress1 >> 24 & 0xff));  
			 				             			        Message mes=myHandler.obtainMessage();
										                	mes.what=0x115;
			 				             			        Bundle bu=new Bundle();
										                	bu.putString("ssid", ssid1);
										                	bu.putString("ipString", ipString1);
										                	bu.putString("password", editText.getText().toString());
										                	bu.putString("capabilities", WifiConnect.pdjm(scanResult.capabilities));
										                	mes.setData(bu);  
										                	myHandler.sendMessage(mes);
															break;
															
														}
			 											try {
			 												Thread.sleep(1000);
			 											} 
			 											catch (InterruptedException e) {
			 												e.printStackTrace();
			 											}
			 											tmp--;
			 										}
			 										if(tmp==0)
			 										{
			 											Message mes=myHandler.obtainMessage();
									                	mes.what=0x110;
		 				             			        Bundle bu=new Bundle();
									                	bu.putString("ssid", scanResult.SSID);
									                	mes.setData(bu);  
									                	myHandler.sendMessage(mes);
			 										}
			 										

			 									}
			 								}).start(); 
			             				}
			             				else
			             				{
			             					new AlertDialog.Builder(WifiConnectActivity.this)    
			             									.setTitle(scanResult.SSID)
			             									.setMessage("Password is wrong")  	
			             									.setPositiveButton("Yes", new OnClickListener() 
			             					    	          {
			             				    	        	  	@Override
			             										public void onClick(DialogInterface dialog, int which) 
			             										{						        	
			             				    	        	  		init();	
			             										}
			             					    	          })  
			             									.show();  
			             				}		             					
									}
			    	          }).show();
						}
						else
						{
		   				 	new AlertDialog.Builder(WifiConnectActivity.this)
			    	          .setTitle(scanResult.SSID)
			    	          .setItems(new String[] { "Capabilities"+":"+getCapabilities(String.valueOf(scanResult.capabilities)), "Signal Strength"+":"+Math.abs(scanResult.level) }, null)
			    	          .setNegativeButton("Cancel", null) 
			    	          .setPositiveButton("Connect", new OnClickListener() 
			    	          {
									@Override
									public void onClick(DialogInterface dialog, int which) 
									{										
										WifiConfiguration wifiConfig=WifiConnect.CreateWifiInfo(scanResult.SSID, password, WifiConnect.pdjm(scanResult.capabilities),wifiManager);
						     			int wcgID = wifiManager.addNetwork(wifiConfig);
						     			if(wifiManager.enableNetwork(wcgID, true))
						     			{
						     				connectedWifiName.setText("Connecting...");
								            connectedWifiIp.setText(null);
						     				new Thread(new Runnable() 
						     				{
			 									@Override
			 									public void run() 
			 									{
			 								    			 								    	
			 								    	
			 										int tmp=11;
			 										while(tmp>0)
			 										{
			 											WifiInfo wifiInfo1=wifiManager.getConnectionInfo();
			 											String ssid1 = FileUtil.check(wifiInfo1.getSSID());
			 											int ipAddress1 = wifiInfo1.getIpAddress();  
			 											if(ssid1!=null&&ipAddress1!=0)
			 											{ 				             			        
			 				             			        String ipString1 = "";
			 				             			        if (ipAddress1 != 0) 
			 				             			        	ipString1 = ((ipAddress1 & 0xff) + "." + (ipAddress1 >> 8 & 0xff) + "." + (ipAddress1 >> 16 & 0xff) + "." + (ipAddress1 >> 24 & 0xff));  
			 				             			        Message mes=myHandler.obtainMessage();
										                	mes.what=0x114;
			 				             			        Bundle bu=new Bundle();
										                	bu.putString("ssid", ssid1);
										                	bu.putString("ipString", ipString1);
										                	mes.setData(bu);  
										                	myHandler.sendMessage(mes);
															break;
															
														}
			 											try {
			 												Thread.sleep(1000);
			 											} 
			 											catch (InterruptedException e) {
			 												e.printStackTrace();
			 											}
			 											tmp--;
			 										}
			 										if(tmp==0)
			 										{
			 											FileUtil.rewrite(scanResult.SSID);
			 						 		        	
			 											Message mes=myHandler.obtainMessage();
									                	mes.what=0x110;
		 				             			        Bundle bu=new Bundle();
									                	bu.putString("ssid", scanResult.SSID);
									                	mes.setData(bu);  
									                	myHandler.sendMessage(mes);
			 										}
			 									}
			 								}).start(); 
						     				
						     			}
						     			else
						     			{
						     				FileUtil.rewrite(scanResult.SSID);
 						 		        						 		        	
	
						     				new AlertDialog.Builder(WifiConnectActivity.this)    
		 									.setTitle(scanResult.SSID)
		 									.setMessage("Password is wrong")  	
		 									.setPositiveButton("Yes", new OnClickListener() 
		 					    	          {
		 				    	        	  	@Override
		 										public void onClick(DialogInterface dialog, int which) 
		 										{						        	
		 				    	        	  		init();	
		 										}
		 					    	          })  
		 									.show();  
						     				
						     			}						     								     			
									}
			    	          }).show();     				
						}
				break;
				}
			}	
		} 
	
	

	    
	 private String getCapabilities(String Capabilities)
	    {
		 	int a=Capabilities.indexOf("WEP");
		 	int b=Capabilities.indexOf("WPA");
		 	int c=Capabilities.indexOf("WPA2");

	    	if(a!=-1)
	    		return "WEP";
	    	else if(b!=-1)
	    	{
	    		if(c!=-1)
	    		{
	    			if(b!=c)
	    				return "WPA/WPA2";
	    			else
	    				return "WPA2";
	    		}
	    		else
	    		{
	    			return "WPA";
	    		}
	    	}
	    	else 
	    		return "empty";
	
	    }

		private void reWifiConnect()
		{
			Intent intent=new Intent(WifiConnectActivity.this,WifiConnectActivity.class);
			startActivity(intent);
			finish();
		}

	 
		public void wifiConnect(View view)
		{
			reWifiConnect();
		}
		
		public void codeManage(View view)
		{
			Intent intent=new Intent(WifiConnectActivity.this,CodeManageActivity.class);
			startActivity(intent);
			finish();
		}
		
		public void changeWifi(View view)
		{
	        if (!wifiManager.isWifiEnabled()) 
	        {  
		         wifiManager.setWifiEnabled(true);
		         TimeThread timethread=new TimeThread();
		         timethread.run();
		         
		    }  
	        else{
	        	wifiManager.setWifiEnabled(false); 
		         TimeThread2 timethread2=new TimeThread2();
		         timethread2.run();
	        }
		}

		@SuppressLint("HandlerLeak")
		class MyHandler extends Handler {
			private Context context;
	        public MyHandler() {
	        }

	        public MyHandler(Context context) {
	        	this.context=context;
	        }
			public MyHandler(Looper L) {
	            super(L);
	        }

	        // ���������д�˷���,�������
	        @Override
	        public void handleMessage(Message msg) {
	            // TODO Auto-generated method stub
	        	if(msg.what==0x110)
	        	{
	        		Bundle b = msg.getData();
		            String ssid = b.getString("ssid");
		            AlertDialog.Builder ad=new AlertDialog.Builder(context)    
						.setTitle(ssid)
						.setMessage("Connect failed!")  	
						.setPositiveButton("Yes",new OnClickListener() 
		    	          {
	    	        	  	@Override
							public void onClick(DialogInterface dialog, int which) 
							{						        	
	    	        	  		init();	
							}
		    	          }); 
 		            
		            if (!isFinishing()) 
		            	ad.show();
	        	}
	        	else if(msg.what==0x114){	        		
		            Bundle b = msg.getData();
		            String ssid = b.getString("ssid");
		            String ipString = b.getString("ipString");		        	
		            connectedWifiName.setText(ssid);
		            connectedWifiIp.setText(ipString);
				}
	        	else if(msg.what==0x115){
	        		
		            Bundle b = msg.getData();
		            String ssid = b.getString("ssid");
		            String ipString = b.getString("ipString");
		            String password = b.getString("password");
		            int capabilities = Integer.parseInt(b.getString("capabilities"));
		            if(capabilities==2)		            
		            	FileUtil.write(ssid, password,"WEP");		            
		            else if(capabilities==3)
		            	FileUtil.write(ssid, password,"WPA");
		            connectedWifiName.setText(ssid);
		            connectedWifiIp.setText(ipString);
				}
	        }
	    }

		public class TimeThread implements Runnable{      // thread  
	        @Override  
	        public void run()
	        {
	        	while(true)
	        	{
	                list = wifiManager.getScanResults();  
			        if (list != null&&list.size()!=0)
			        {
				         init();
				         break;
				    } 

		        	try{  
		        		Thread.sleep(1000);     // sleep 1000ms  
		            }
		        	catch (Exception e) 
		        	{  
		        		e.printStackTrace();
		            }
	        	}
	        }  
	    }  
		
		public class TimeThread2 implements Runnable{      // thread  
	        @Override  
	        public void run()
	        {
	        	while(true)
	        	{
			        if (!wifiManager.isWifiEnabled()) 
			        {
				         init();
				         break;
				    }  
		        	try{  
		        		Thread.sleep(1000);     // sleep 1000ms  
		            }
		        	catch (Exception e) 
		        	{  
		        		e.printStackTrace();
		            }
	        	}

	        }  
	    }  	
	
		@Override
		public void onBackPressed()
		{
			if(isLoad==false)
				finish();
			else{
				showInterstitial();
				exit();
			}

			
			
		}


		 private void exit() {
		        if (!isExit) {
		            isExit = true;
		        } else {
		            finish();
		        }
		    }
		private void adinit() {
			// TODO Auto-generated method stub
			
			
		    AdView adView = (AdView) this.findViewById(R.id.adView1);
		    AdRequest adRequestBanner = new AdRequest.Builder().build();

		    adView.loadAd(adRequestBanner);
		    
		    isLoad=false;
		    interstitialAd = new InterstitialAd(this);
		    interstitialAd.setAdUnitId("ca-app-pub-6475651336232944/8988360917");
		    interstitialAd.setAdListener(new AdListener() {
		        @Override
		        public void onAdLoaded() {

		        	isLoad=true;
		        }


		      });
		    
		    AdRequest adRequestInterstitial = new AdRequest.Builder().build();
		    interstitialAd.loadAd(adRequestInterstitial);
		}
		
		  public void showInterstitial() {
			    // Disable the show button until another interstitial is loaded.

			    if (interstitialAd.isLoaded()) {
			      interstitialAd.show();
			    } 
			  }
}
